package cn.com.xy.sms.util;

import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import cn.com.xy.sms.sdk.Iservice.OnlineUpdateCycleConfigInterface;
import cn.com.xy.sms.sdk.db.entity.ContactsColumns;
import cn.com.xy.sms.sdk.dex.DexUtil;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.provider.ContactsProvider;
import cn.com.xy.sms.sdk.util.StringUtils;

/* SMARTISAN-188 likuangkuang 20161110 start, add new interface and code refactor */
public final class ParseContactManager {
    private static final String TAG = "ParseContactManager";

    private static Cursor getCursor(Context ctx, String phoneNumber, String[] projection) {
        if (ctx == null || TextUtils.isEmpty(phoneNumber)) {
            return null;
        }

        // 优化：使用户输入带“-”的字符也能搜索到配合的结果
        phoneNumber = phoneNumber.replace("-", "");

        ContentResolver resolver = ctx.getContentResolver();
        Uri uri = Uri.parse(ContactsProvider.URI);

        // 构造 where 子句和查询的字段
        StringBuffer selection = new StringBuffer(ContactsColumns.PHONE);
        selection.append(" = '").append(phoneNumber).append("'");

        Cursor cursor = resolver.query(uri, projection, selection.toString(), null, null);
        if (cursor != null && cursor.moveToFirst()) {
            // 若不在有效期内，删除数据，并返回空
            long updateTime = cursor.getLong(cursor.getColumnIndex(ContactsColumns.UPDATE_TIME));
            long updateCycle = DexUtil.getUpdateCycleByType(OnlineUpdateCycleConfigInterface.TYPE_QUERY_CONTACTS_CYCLE,
                    ContactsColumns.UPDATE_CYCLE);
            if (System.currentTimeMillis() - updateTime > updateCycle) {
                resolver.delete(uri, ContactsColumns.PHONE + " = ?", new String[] { phoneNumber });
                cursor.close();
                return null;
            }
        }

        return cursor;
    }

    /**
     * 根据电话号码获取信息数据
     * 
     * @param ctx
     *            上下文
     * @param phoneNumber
     *            电话号码
     * @param extend
     *            扩展数据
     * @return JSONArray object
     * @throws Exception
     *             异常
     */
    public static JSONArray getExtendForContact(Context ctx, String phoneNumber, Map<String, String> extend) {
        JSONArray array = new JSONArray();
        Cursor cursor = getCursor(ctx, phoneNumber, new String[] { ContactsColumns.DATA, ContactsColumns.UPDATE_TIME });
        try {
            if (cursor != null && cursor.moveToFirst()) {
                do {
                    String data = cursor.getString(cursor.getColumnIndex(ContactsColumns.DATA));
                    if (!StringUtils.isNull(data)) {
                        array.put(new JSONObject(data));
                    }
                } while (cursor.moveToNext());
            }
        } catch (Throwable t) {
            LogManager.e(TAG, "getExtendForContact", t);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }

        return array;
    }

    /**
     * 根据电话号码获取信息数据
     * 
     * @param ctx
     *            上下文
     * @param phoneNumber
     *            电话号码
     * @param extend
     *            扩展数据
     * @return String name
     * @throws Exception
     *             异常
     */
    public static String getMsgForContact(Context ctx, String phoneNumber, Map<String, String> extend) {
        // 在数据库中查询数据
        String name = null;
        Cursor cursor = getCursor(ctx, phoneNumber, new String[] { ContactsColumns.NAME, ContactsColumns.UPDATE_TIME });
        if (cursor != null && cursor.moveToFirst()) {
            name = cursor.getString(cursor.getColumnIndex(ContactsColumns.NAME));
        }

        if (cursor != null) {
            cursor.close();
        }

        return TextUtils.isEmpty(name) ? null : name;
    }
}
/* SMARTISAN-188 likuangkuang 20161110 end */
